function showVideoInfos(event,k){
    var title=k.getAttribute('vidtitle');
    var metatags=k.getAttribute('vidmetatags');
    var testo = "<strong>"+title+"</strong><br/>";
    testo += "Metatags<br/>"+metatags;
    var q = document.getElementById('hint');
    if(q!=undefined)
        q.parentNode.removeChild(q);
    var x = event.pageX;
    var y = event.pageY;
    var hint;
    var evento = document.getElementById('eventi');
    hint = document.createElement('div');
    hint.style.position = 'absolute';
    hint.style.top = (y+12)+'px';
    hint.style.left = (x+12)+'px';
    hint.style.border = '3px solid black';
    hint.style.backgroundColor = '#ffff88';
    hint.setAttribute('id', 'hint');
    hint.style.padding = '5px';
    hint.innerHTML = ''+testo;
    evento.appendChild(hint);

}

/**
 * Elimina il div degli hint
 * @author andrea
 */
function hideVideoInfos(){
    var x = document.getElementById('hint');
    x.parentNode.removeChild(x);
}

/**
 * Avvia la ricerca dei video
 * @param {string} containerId, il container nel quale inserire il risultato
 * @param {string} noadmin, true se la chiamata viene effettuata da NON amministratore
 */
function searchVideos(containerId,noadmin){
    noadmin = noadmin || "";
    $('#nextPagination').css("display","none");
    $('#prevPagination').css("display","none");
    if(noadmin){
        noadmin = "wp-admin/";
        var home = "&home=true";
    }
    var form = document.searchVideosPalinsesto;
    var querystring = 'action=searchVideosPalinsesto&dateSearch='+form.dateSearch.value+'&metatagSearch='+
        form.metatagSearch.value+'&categorySearch='+form.categorySearch[form.categorySearch.selectedIndex].value+home;
    disableClick();
    $.ajax({
        method: "post",
        url: location.href.substring(0,location.href.lastIndexOf('/')+1)+noadmin+"admin-ajax.php",
        data: querystring, 
        success: function(response){
            
            if(response == false)
                response = "<div align='center'><strong>La ricerca non ha prodotto risultati</strong></div>";
            var string = response.substring(0,response.lastIndexOf('>')+1);
            $("#"+containerId).hide("slow",function(){
                $(this).html(string);
                $("#"+containerId).show("slow");
                });
            if(noadmin == "")
                checkPagination('nextPagination','prevPagination');
            else
                checkPagination('nextPagination','prevPagination',noadmin);
            enableClick();
        }
    });

    
}

/**
 * Torna all'inizio della pagina in modo graduale
 * @param {string} k Necessario alla funzione per essere utilizzata, ma quando questa
 * viene chiamata non deve essere passato (è un indice che la funzione ricava da sé)
 * @author Andrea
 */
function scrollUp(k){
    k = k || 0;
    var tmp;
    k = parseInt(k);
    
    var offset = window.pageYOffset;
    eval('tmp ='+offset+'-'+k);
    k=k+1;
    window.scrollTo(0,tmp);
    if(offset!=0)
        setTimeout('scrollUp(\''+k+'\')', 5);
    else{
        return;}
}


function addVideoToList(infoContainer){
    var id = $("#"+infoContainer).attr('vidid');
    if(isAlreadyInList(id)){
        alert("Il video e' gia' presente nella lista");
        block_animation_add_video = true;
        return;
    }
    block_animation_add_video = false;
    var thumb = $("#"+infoContainer).attr('vidthumb');
    var bigthumb = $("#"+infoContainer).attr('vidbigthumb');
    var title = $("#"+infoContainer).attr('vidtitle');
    var description = $("#"+infoContainer).attr('viddesc');
    var path = $("#"+infoContainer).attr('vidpath');
    var remove = "<div onclick='removeVideoFromList(this);' class='removeButton'></div>";
    var tableRow = "<tr class=\"listElement\" vidtitle=\""+title+"\" vidbigthumb=\""+bigthumb+"\" vidid=\""+id+"\" viddesc=\""+description+"\" vidpath=\""+path+"\" vidthumb=\""+thumb+"\" name='inTheList' onclick='selectFromList(this)'><td class=\"inTheList_thumbTd\">\n\
            <div id=\"videoThumbList"+id+"\" class=\"thumbs\">"+remove+"</div></td>\n\
            <td class='titletd'><strong>"+title+"</strong></td>";
    tableRow += "<input type='hidden' name='palinsesto[]' value='"+id+"'/></tr>"
    var table = document.getElementById("videoList").getElementsByTagName('table');
    table[0].innerHTML = table[0].innerHTML+tableRow;
    $("#videoThumbList"+id).css("background-image","url('"+thumb+"')");
    
    
}

function selectFromList(container){
    var selected = container.getAttribute('selected');

    var i;
    if(selected != 'selected'){
        var list = document.getElementsByName("inTheList");
        for(i=0;i<=list.length;i++){
            $(list[i]).removeAttr('selected');
            $(list[i]).removeClass('selectedItem');
        }
        $(container).attr('selected','selected');
        selected = $(container).attr('selected');
        $(container).addClass('selectedItem');
    }
    else{
        $(container).removeAttr('selected');
        $(container).removeClass('selectedItem');}
    
}

function removeSelectedItem(){
    var selected = getSelected();
    if(selected == false){
        alert("Nessun video selezionato")
        return;
        }
    else
        $(selected).hide("slow",function(){$(this).parent().remove()});
}

function removeVideoFromList(element){
    $(element).hide(300,function(){
        $(this).parent().parent().parent().hide(300);
        $(this).parent().parent().parent().remove();
    });
}

/**
 * 
 * @return l'id del container selezionato, false se nessun selezionato
 */
function getSelected(){
    var list = document.getElementsByName("inTheList");
    var i;var selected;
    if(list.length == 0){
        return false}
    for(i=0;i<list.length;i++){ 
        selected = list[i].getAttribute('selected');
        if(selected == 'selected'){
            return list[i];
        }
    }
    return false;
}

function changeOrder(up_down){
    var selected = getSelected();
    if(selected == false){
        alert('Nessun elemento selezionato');
        return;}
    var parent;var brother;
    if(up_down == "down"){
        parent = $(selected).parent();
        brother = $(selected).parent().next();
        if($(brother).attr("class") == "listElement"){
            $(selected).hide("slow",function(){
                $(parent).remove();
                $(brother).after($(parent));
                $(parent).children().show("slow");
                });
            return;}
    }
    if(up_down == "up"){
        parent = $(selected).parent();
        brother = $(selected).parent().prev();
        if($(brother).attr("class") == "listElement"){    
             $(selected).hide("slow",function(){
                $(parent).remove();
                $(brother).before($(parent));
                $(parent).children().show("slow");
                });
            return;}
    }
    alert('Impossibile effettuare l\'operazione');
    return;
}

function isAlreadyInList(vidid){
    var list = document.getElementsByName("inTheList");
    var i;
    
    if(list.length == 0){
        return false}
    
    for(i=0;i<list.length;i++){ 
        if($(list[i]).attr("vidid")==vidid){
            return true;
        }
        }
    return false;
}

function videoInPalinsesto(){
    var list = document.getElementsByName("inTheList");    
    if(list.length == 0){
        return false}
    return true;
}

function submitPalinsesto(){
    var date = $('#onairDate').val();
    var title = $('#paltitle').val();
    if(!check_title(title)){
        if(title == "")
            alert('Devi inserire un titolo');
        else
            alert('Ci sono caratteri non ammessi nel titolo');
        return;
    }
    if(!check_date_mdY(date)){
        if(date == "")
            alert("Devi inserire una data.");
        else
            alert("C'e' un errore nella data.");
        return;
    }
    if(!videoInPalinsesto()){
        alert("Nessun video nel palinsesto");
        return;
    }
    $("#videoListForm").submit();
        
}

function getNextResults(direction,containerId,noadmin){
    noadmin = noadmin || "";
    $('#nextPagination').css("display","none");
    $('#prevPagination').css("display","none");
    var home = "";
    if(noadmin){
        noadmin = "wp-admin/";
        home = "&home=true";
    }
    var querystring = 'action=paginationPalinsesto&fwd_bck='+direction+home;
    disableClick();
    $.ajax({
        method: "post",
        url: location.href.substring(0,location.href.lastIndexOf('/')+1)+noadmin+"admin-ajax.php",
        data: querystring, 
        success: function(response){
            if(response == false){
                response = "<div align='center'><strong>La ricerca non ha prodotto risultati</strong></div>";
                }
            var string = response.substring(0,response.lastIndexOf('>')+1);
            $("#"+containerId).hide("blind","slow",function(){
                $(this).html(string);
                $("#"+containerId).show("blind","slow");
                });
            if(noadmin == "")
                checkPagination('nextPagination','prevPagination');
            else
                checkPagination('nextPagination','prevPagination',noadmin);
            enableClick();
        }
    });
    
}

function checkPagination(next,prev,noadmin){
    noadmin = noadmin || "";
    if(noadmin)
        noadmin = "wp-admin/";
    var querystring = 'action=checkPagination';
    disableClick();
    $.ajax({
        method: "post",
        url: location.href.substring(0,location.href.lastIndexOf('/')+1)+noadmin+"admin-ajax.php",
        data: querystring, 
        success: function(response){
            response = response.substring(0,response.length-1);
            var data = getArray(response);
            if(data['fwd'] == "0"){
               
           }
            else
                $('#'+next).show("slide",'slow');
            if(data['bck'] == 0){
                //$('#'+prev).hide("slide",'slow');
            }
            else
                $('#'+prev).show("slide",'slow');
            enableClick();
        }
    });
}

function appendButtonsPalinsesto(container,infoContainer){
    var addTitle = "<div id=\"addTitle\">"+$("#"+infoContainer).attr("vidtitle")+"</div>";
    var clr = "<div class='clr'></div>";
    var addButton = "<div class='floatl' id='addButton' onclick=\"addVideoToList('"+infoContainer+"');moveVideoEffect(event,this);\"></div>";
    var playButton = "<div class='floatl' id='playButton' onclick=\"playVideo('"+infoContainer+"','palinsesto');\"></div>";
        if($("#addButton").length == 0){
            $(container).html(addTitle+$(container).html()+addButton+playButton+clr);
            $("#addButton").fadeIn("fast");
            $("#playButton").fadeIn("fast");
            $("#addTitle").fadeIn("fast");
        }
        if($(container).find("#addButton").length == 0 && $("#addButton").length != 0){
            $("#addButton").remove();
            $("#addTitle").remove();
            $("#playButton").remove();
            $(container).html(addTitle+$(container).html()+addButton+playButton+clr);
            $("#addButton").fadeIn("fast");
            $("#addTitle").fadeIn("fast");
            $("#playButton").fadeIn("fast");
    }
    
}

function removeButtonsPalinsesto(){
        $("#addButton").fadeOut(100,function(){
            $(this).remove();
            });
        $("#addTitle").fadeOut(100,function(){
            $(this).remove();
            });
        $("#playButton").fadeOut(100,function(){
            $(this).remove();
            });
}

function moveVideoEffect(event,elementToMove){
    if(block_animation_add_video == true){
        block_animation_add_video = false;
        return;
    }
    var x = event.pageX;
    var y = event.pageY;
    var obj = $(elementToMove).parent().clone();
    
    $(obj).css("position","absolute");
    $(obj).css('left',x+"px");
    $(obj).css('top',y+"px");
    $(obj).css('opacity','0.5');
    $("#eventi").append(obj);
    var offset = $("#animationTarget").offset();
    $(obj).animate({
        top: offset.top+"px",
        left: offset.left+"px",
        opacity: 0
    },400,function(){
        $(this).remove();
    });
    
}

function playVideo(infoContainer){
    var newPath;
    var blackdiv = "<div class='blackdiv'></div>"
    $("#eventi").append(blackdiv);
    $(".blackdiv").css("width",$(document).width()+"px");
    $(".blackdiv").css("height",$(document).height()+"px");
    $(".blackdiv").fadeIn(700,function(){
        var add;
        var plwidth = 500;
        var plheight = 350;
        var padding = 50;
        add = "<div onclick='addVideoPlayToPalinsesto(\""+infoContainer+"\");' class='addButton'></div>";
        newPath = $("#"+infoContainer).attr("vidpath");
        var close = "<div onclick='closeVideoPlay();' class='closeButton'></div>";
        var palette = "<div  id='palette'>"+close+add+"</div>";
        var player = "<div id='player'><div id='player_in'></div></div>";
        var margin_lateral = parseInt(($(window).width()-plwidth)/2);
        var margin_top_bottom = parseInt(($(window).height()-plheight)/2);
        $("#eventi").append(player);
        $("#player").css("display","none");
        $("#player").css("z-index","1000");
        $("#player").css("position","absolute");
        $("#player").css("background-color","white");
        $("#player").css("padding",padding+"px");
        $("#player").css("top","0");
        $("#player").css("left","0");
        $("#player").css("margin-left",margin_lateral+"px");
        $("#player").css("margin-right",margin_lateral+"px");
        $("#player").css("margin-bottom",margin_top_bottom+"px");
        $("#player").css("margin-top",margin_top_bottom+"px");
        $("#player").css("width",plwidth+"px");
        $("#player").css("height",plheight+"px");
        $("#player").show("slow",function(){
            jwplayer("player_in").setup({
              flashplayer: '../wp-content/plugins/video-wizard/libs/jwplayer/player.swf',
              file: newPath,
              autoplay: true,
              controlbar: "bottom",
              width: plwidth,
              height: plheight,
              provider: "http",
              "http.startparam":"start"
             });
           
           $("#eventi").append(palette);
           var palette_margin_lat = $(window).width()+(2*padding)-margin_lateral+10;
           var palette_margin_top = $(window).height()-($(window).height()-(2*margin_top_bottom)+(3*padding));
           $("#palette").css('margin-left',palette_margin_lat+"px");
           $("#palette").css('margin-top',palette_margin_top+"px");
           $("#palette").show('slow');
           
        });
    });
}

function closeVideoPlay(){
    $("#player").fadeOut("slow",function(){
        $(this).remove();
        $("#palette").fadeOut("slow",function(){
                $(this).remove();
                $(".blackdiv").fadeOut("slow",function(){
                    $(this).remove();
            });
    });
    });   
}

function addVideoPlayToPalinsesto(infoContainer){
    addVideoToList(infoContainer);
    closeVideoPlay();
}

function editVideo(infoContainer){
    var co = "#"+infoContainer;
    var vidtitle = $(co).attr("vidtitle");
    var viddesc = $(co).attr("viddesc");
    var vidmetatags = $(co).attr("vidmetatags");
    var vidcat = $(co).attr("vidcat");
    $("#modvid-title").attr("value",vidtitle);
    $("#modvid-title").animate({
        backgroundColor: '#ffcccc'
    },500,function(){
        $("#modvid-description").attr("value",viddesc);
        $("#modvid-description").animate({
            backgroundColor:'#ffcccc'
        },500,function(){
            $("#modvid-metatags").attr("value",vidmetatags);
            $("#modvid-metatags").animate({
                backgroundColor:"#ffcccc"
            },500,function(){$(this).animate({},1000,function(){
                $("#modvid-title").animate({
                    backgroundColor: 'white'
                },500,function(){
                    $("#modvid-description").animate({
                        backgroundColor:'white'
                    },500,function(){
                        $("#modvid-metatags").animate({
                            backgroundColor:"white"
                        },500)
                    })
                });    
                    
            })})
        })
    });
    
}


